package com.diamond.controller;

import com.diamond.pojo.ProductInfo;
import com.diamond.pojo.vo.ProductInfoVo;
import com.diamond.service.ProductInfoService;
import com.github.pagehelper.PageInfo;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/prod")
public class ProductInfoAction {

    public static final int PAGE_SIZE = 5;
    //ajax异步请求上传的图片名称
    private String newFileName;

    @Autowired
    ProductInfoService productInfoService;

    @RequestMapping("/getAll")
    public String getAll(Model model) {
        List<ProductInfo> products = productInfoService.getAll();
        model.addAttribute("products",products);
        return "product";
    }

    /**
     * 分页显示第一页
     * @param model
     * @return
     */
    @RequestMapping("/split")
    public String split(Model model,HttpSession session) {

        PageInfo<ProductInfo> info = productInfoService.splitPage(1,PAGE_SIZE);
        model.addAttribute("info",info);
        return "product";
    }

    /**
     * ajax异步处理分页请求
     * @ResponseBody 标记处理ajax请求
     * @param vo
     * @param session
     */
    @ResponseBody
    @RequestMapping("/ajaxSplit")
    public void ajaxSplit(ProductInfoVo vo, HttpSession session) {

        PageInfo<ProductInfo> info = null;
        Object uProdVo = session.getAttribute("prodVo");
        if (uProdVo != null){
            //说明发生的是带多条件查询的分页
            info = productInfoService.splitPageCondition((ProductInfoVo) uProdVo,PAGE_SIZE);
            /*
                若不移除则会发生下一次请求不是带多条件查询的分页，
                但因为没有移除而发生vo != null的判断
            */
            session.removeAttribute("prodVo");
        }else {
            info = productInfoService.splitPageCondition(vo,PAGE_SIZE);
        }
        //异步请求传递的参数放在session域中
        session.setAttribute("info",info);
    }

    /**
     * ajax异步请求做文件上传并回显
     * @param pimage
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/ajaxImg")
    public Object ajaxImg(MultipartFile pimage, HttpServletRequest request) {
        //1.修改上传的文件的文件名解决重名
        String fileName = pimage.getOriginalFilename();
        //获取后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //生成UUID
        String uuId = UUID.randomUUID().toString().replaceAll("-","");
        //拼接成新的文件名
        newFileName = uuId + suffix;
        //2.将文件保存至指定位置
        String realPath = request.getServletContext().getRealPath("/image_big");
        //File.separator表示/
        String finalPath = realPath + File.separator + newFileName;
        try {
            pimage.transferTo(new File(finalPath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //3.将图片名称封装为json对象返回到ajax
        JSONObject object = new JSONObject();
        object.put("imgurl",newFileName);
        return object.toString();
    }

    /**
     * 新增商品信息
     * @param info
     * @return
     */
    @RequestMapping("/save")
    public String save(ProductInfo info,Model model) {
        //表单提交上的数据缺少图片名称以及上架日期，前后顺序要与数据库一致
        info.setpImage(newFileName);
        info.setpDate(new Date());
        //保存至数据库
        int i = -1;
        try {
            i = productInfoService.save(info);
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        if (i > 0) {
            model.addAttribute("msg","增加成功！");
        } else {
            model.addAttribute("msg","增加失败！");
        }
        //便于判断更新商品信息时是否有上传过商品图片
        newFileName = "";
        return "forward:/prod/split.action";
    }

    /**
     * 更新商品界面商品信息回显
     * @param pid
     * @param model
     * @return
     */
    @RequestMapping("/one")
    public String getOne(Integer pid, Model model,HttpSession session,ProductInfoVo vo) {
        ProductInfo info = productInfoService.getById(pid);
        //存放在session域中，便于更新信息完成后(包含两次请求)取出分页信息
        session.setAttribute("prodVo",vo);
        model.addAttribute("prod",info);
        return "update";
    }

    /**
     * 更新商品信息
     * @param info
     * @param session
     * @return
     */
    @RequestMapping("/update")
    public String update(ProductInfo info,HttpSession session) {
        //newFileName不为空则有上传过新图片,否则没有
        if (!"".equals(newFileName)) {
            info.setpImage(newFileName);
        }
        int num = -1;
        try {
            num = productInfoService.update(info);
        } catch (Exception exception) {
            exception.printStackTrace();
        }

        if (num>0) {
            session.setAttribute("msg","更新成功!");
        } else {
            session.setAttribute("msg","更新失败!");
        }
        newFileName = "";
        return "forward:/prod/ajaxSplit.action";
    }

    /**
     * 删除商品
     * 此处是ajax异步请求的一部分，请求转发到的方法仍然是ajax异步请求
     * 若是添加@ResponseBody则会导致转发到的方法无法当作ajax异步请求来解析
     * @param pid
     * @param request
     * @return
     */
    @RequestMapping("/delete")
    public String delete(Integer pid,HttpServletRequest request,ProductInfoVo vo) {
        int num = -1;
        num = productInfoService.delete(pid);
        if (num > 0) {
            request.setAttribute("msg","删除成功!");
            request.getSession().setAttribute("deleteProdVo",vo);
        } else {
            request.setAttribute("msg","删除失败!");
        }

        return "forward:/prod/deleteAjaxSplit.action";
    }

    /**
     * 用来删除商品后显示商品分页
     * 单独写是因为info中的数据发生了变化
     * produces = "text/html;charset=UTF-8" 设置返回字符串的字符编码
     * @param request
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/deleteAjaxSplit",produces = "text/html;charset=UTF-8")
    public Object deleteAjaxSplit(HttpServletRequest request,HttpSession session) {
        PageInfo<ProductInfo> info = null;
        Object vo = session.getAttribute("deleteProdVo");
        if (vo != null) {
            info = productInfoService.splitPageCondition((ProductInfoVo) vo,PAGE_SIZE);
            session.removeAttribute("deleteProdVo");
        }else {
            info = productInfoService.splitPage(1,PAGE_SIZE);
        }
        session.setAttribute("info",info);
        return request.getAttribute("msg");
    }

    /**
     * 批量删除
     * @param pids
     * @param request
     * @return
     */
    @RequestMapping("/deleteBarth")
    public String deleteBarth(String pids,HttpServletRequest request) {
        //将上传的字符串转化成数组
        String[] ps = pids.split(",");
        try {
            int i = productInfoService.deleteBarth(ps);
            if (i > 0) {
                request.setAttribute("msg","批量删除成功！");
            } else {
                request.setAttribute("msg","批量删除失败！");
            }
        } catch (Exception exception) {
            request.setAttribute("msg","商品不可被删除！");
        }

        return "forward:/prod/deleteAjaxSplit.action";
    }

    @ResponseBody
    @RequestMapping("/condition")
    public void condition(ProductInfoVo vo,HttpSession session) {
        List<ProductInfo> productInfos = productInfoService.selectCondition(vo);
        session.setAttribute("list",productInfos);
    }

}
